<template>
  <a-card :body-style="{ padding: '0' }" :bordered="false">
    <a-form-model
      ref="ruleForm"
      :model="formData"
      :rules="rules"
      :label-col="{ lg: { span: 5 }, sm: { span: 5 } }"
      :wrapper-col="{ lg: { span: 10 }, sm: { span: 10 } }"
    >
      <a-form-model-item label="优惠券类型" prop="couponType">
        <a-radio-group
          v-model="formData.couponType"
          :disabled="handle == 'view'"
          :options="couponList"
          @change="handleChanage"
        ></a-radio-group>
      </a-form-model-item>

      <a-form-model-item label="优惠券名称" prop="couponName">
        <a-input
          v-model="formData.couponName"
          :disabled="handle == 'view'"
          :maxLength="10"
          name="couponName"
          placeholder="请输入10个字以内的优惠券名称"
        />
      </a-form-model-item>

      <a-form-model-item
        prop="discountRatio"
        v-if="formData.couponType == 2 || formData.couponType == 4"
      >
        <template slot="label">
          <span class="ant-form-item-required">优惠内容</span>
        </template>
        <div>
          打
          <a-input-number
            v-model="formData.discountRatio"
            :disabled="handle == 'view'"
            :min="0.0"
            :max="9.9"
            :precision="1"
          ></a-input-number>
          折
        </div>
        <a-checkbox-group
          v-model="formData.mostDiscountCustom"
          :disabled="handle == 'view'"
        >
          <a-checkbox :value="1"
            >最多优惠
            <a-input-number
              v-model="formData.mostDiscount"
              :disabled="handle == 'view'"
              :min="0.0"
              :max="99999999"
              :precision="2"
            ></a-input-number>
            元</a-checkbox
          >
        </a-checkbox-group>
      </a-form-model-item>

      <a-form-model-item
        label="金额"
        prop="couponAmount"
        v-if="
          formData.couponType == 0 ||
          formData.couponType == 1 ||
          formData.couponType == 3
        "
      >
        <a-input-number
          style="width: 200px"
          v-model="formData.couponAmount"
          :disabled="handle == 'view'"
          :min="0"
          :max="10000"
          :precision="0"
          name="couponAmount"
          placeholder="请输入优惠券金额"
        />
      </a-form-model-item>

      <a-form-model-item label="使用门槛" prop="couponFullMoneyType">
        <a-radio-group
          v-model="formData.couponFullMoneyType"
          :disabled="handle == 'view'"
          @change="handleCouponFullMoneyChange"
        >
          <a-radio
            :value="2"
            style="display: block; height: 40px; line-height: 40px"
            >无门槛</a-radio
          >
          <a-radio
            :value="1"
            style="display: block; height: 40px; line-height: 40px"
          >
            <a-space>
              订单满
              <a-input-number
                :min="0"
                :max="999999"
                :precision="2"
                v-model="formData.couponFullMoney"
                :disabled="handle == 'view'"
              />
              可用
            </a-space>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item
        v-if="formData.couponType == 3 || formData.couponType == 4"
        prop="couponIssueType"
      >
        <template slot="label">
          <span class="ant-form-item-required">发放方式</span>
        </template>
        <a-radio-group
          v-model="formData.couponIssueType"
          :disabled="handle == 'view'"
        >
          <a-radio
            style="display: block; height: 40px; line-height: 40px"
            :value="0"
            >用户领取</a-radio
          >
          <a-radio
            style="display: block; height: 40px; line-height: 40px"
            :value="4"
            >系统发放</a-radio
          >
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item v-else prop="couponIssueTypeCustom">
        <template slot="label">
          <span class="ant-form-item-required">发放方式</span>
        </template>
        <a-radio-group
          v-model="formData.couponIssueTypeCustom"
          :disabled="handle == 'view'"
          @change="handleCouponIssueTypeChange"
        >
          <a-radio
            style="display: block; height: 40px; line-height: 40px"
            v-for="(item, index) in distributionMethod"
            :key="index"
            :value="item.value"
            @change="handleCouponIssueTypeCustomChange"
          >
            <a-space>
              {{ item.label }}
              <a
                href="javascript:;"
                v-if="item.value == 1 && formData.couponIssueTypeCustom == 1"
                @click="showDistributionConditions = true"
                >请选择发放条件</a
              >
            </a-space>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item prop="couponIssueType">
        <template slot="label">
          <span class="ant-form-item-required">使用用户</span>
        </template>
        <a-radio-group
          v-model="formData.useCustomerType"
          :disabled="handle == 'view'"
          @change="handleUseCustomerTypeChange"
        >
          <a-radio
            style="display: block; height: 40px; line-height: 40px"
            v-for="(item, index) in useUserList"
            :key="index"
            :value="item.value"
          >
            <a-space>
              {{ item.label }}
              <a
                href="javascript:;"
                v-if="item.value == 1 && formData.useCustomerType == 1"
                @click="showMemberLevel = true"
                >请选择会员等级</a
              >
              <a
                href="javascript:;"
                v-if="item.value == 2 && formData.useCustomerType == 2"
                @click="showCustomList = true"
                >请选择客户列表</a
              >
            </a-space>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item prop="couponUseType">
        <template slot="label">
          <span class="ant-form-item-required">使用商品</span>
        </template>
        <a-radio-group
          v-model="formData.couponUseType"
          :disabled="handle == 'view'"
          @change="handleCouponUseTypeChange"
        >
          <a-radio
            style="display: block; height: 40px; line-height: 40px"
            v-for="(item, index) in useGoodsList"
            :key="index"
            :value="item.value"
          >
            <a-space>
              {{ item.label }}
              <a
                href="javascript:"
                v-if="item.value == 2 && formData.couponUseType == 2"
                @click="handleShowEnableGoodsChange"
                >请选择商品</a
              ><!--enableGoods-->
              <a
                href="javascript:"
                v-if="item.value == 4 && formData.couponUseType == 4"
                @click="handleShowNotEnableGoodsChange"
                >请选择商品</a
              ><!--notEnableGoods-->
              <a
                href="javascript:"
                v-if="item.value == 1 && formData.couponUseType == 1"
                @click="handleShowEnableGoodsGroupChange"
                >请选择分类</a
              ><!--enableGoodsGroup-->
              <a
                href="javascript:"
                v-if="item.value == 3 && formData.couponUseType == 3"
                @click="handleShowNotEnableGoodsGroupChange"
                >请选择分类</a
              ><!--notEnableGoodsGroup-->
            </a-space>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item prop="couponOwnWay">
        <template slot="label">
          <span class="ant-form-item-required">优惠券获取方式</span>
        </template>
        <a-radio-group
          v-model="formData.couponOwnWay"
          :disabled="handle == 'view'"
        >
          <a-radio
            v-for="(item, index) in acquisitionMethodList"
            :key="index"
            :value="item.value"
          >
            {{ item.label }}
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item prop="allowGift">
        <template slot="label">
          <span class="ant-form-item-required">是否允许转赠</span>
        </template>
        否
        <!-- <a-radio-group v-model="formData.allowGift" :options="allowGiftList"></a-radio-group> -->
      </a-form-model-item>

      <a-form-model-item>
        <template slot="label">
          <span class="ant-form-item-required">是否允许积分兑换</span>
        </template>

        <a-radio-group
          v-model="formData.redeemStatus"
          :disabled="handle == 'view'"
          @change="redeemExChange"
        >
          <a-radio
            :value="0"
            style="display: block; height: 40px; line-height: 40px"
            >否</a-radio
          >
          <a-radio
            :value="1"
            style="display: block; height: 40px; line-height: 40px"
          >
            <a-space>
              <a-input-number
                :min="0"
                :max="999999"
                v-model="formData.redeemAmount"
                :disabled="handle == 'view'"
              />
            </a-space>
            积分兑换
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item prop="couponTotalCustom">
        <template slot="label">
          <span class="ant-form-item-required">发放总量</span>
        </template>
        <a-radio-group
          v-model="formData.couponTotalCustom"
          :disabled="handle == 'view'"
          @change="handleCouponTotalChange"
        >
          <a-radio
            :value="1"
            style="display: block; height: 40px; line-height: 40px"
          >
            <a-space>
              发放总量
              <a-input-number
                :min="0"
                :max="999999"
                :precision="0"
                v-model="formData.couponTotal"
                :disabled="handle == 'view'"
              />
            </a-space>
          </a-radio>
          <a-radio
            :value="2"
            style="display: block; height: 40px; line-height: 40px"
            >不限量</a-radio
          >
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item label="限领总量" prop="couponLimit">
        <a-input-number
          style="width: 200px"
          v-model="formData.couponLimit"
          :disabled="handle == 'view'"
          name="couponLimit"
          :min="1"
          :max="99999999"
          :precision="0"
          placeholder="请输入限领总量"
        />
      </a-form-model-item>

      <a-form-model-item label="优惠券说明" prop="couponDesc">
        <a-textarea
          rows="4"
          placeholder="请输入128个以内的优惠券说明"
          v-model="formData.couponDesc"
          :disabled="handle == 'view'"
          :maxLength="128"
        />
      </a-form-model-item>

      <a-form-model-item prop="">
        <template slot="label">
          <span class="ant-form-item-required">领取时间范围</span>
        </template>

        <a-radio-group
          v-model="formData.receiveTimeType"
          :disabled="handle == 'view'"
          @change="receiveTimeTypeChange"
        >
          <template v-if="formData.couponType == 3 || formData.couponType == 4">
            <a-radio
              :value="1"
              style="display: block; height: 40px; line-height: 40px"
            >
              随时可领取
            </a-radio>
            <a-radio
              :value="2"
              style="display: block; height: 40px; line-height: 40px"
            >
              新用户注册
              <template v-if="formData.receiveTimeType == 2">
                <a-input
                  type="number"
                  v-model="formData.receiveTimeAmount"
                  :disabled="handle == 'view'"
                  style="width: 100px"
                ></a-input>
                （x*24h）天内可领取
              </template>
            </a-radio>
            <a-radio
              :value="3"
              style="display: block; height: 40px; line-height: 40px"
            >
              用户生日
              <template v-if="formData.receiveTimeType == 3">
                <a-input
                  type="number"
                  v-model="formData.receiveTimeAmount"
                  :disabled="handle == 'view'"
                  style="width: 100px"
                ></a-input>
                天内可领取
              </template>
            </a-radio>
            <a-radio
              :value="4"
              style="display: block; height: 40px; line-height: 40px"
            >
              用户升级
              <template v-if="formData.receiveTimeType == 4">
                <a-input
                  type="number"
                  v-model="formData.receiveTimeAmount"
                  :disabled="handle == 'view'"
                  style="width: 100px"
                ></a-input>
                天内可领取
              </template>
            </a-radio>
            <a-radio
              :value="5"
              style="display: block; height: 40px; line-height: 40px"
            >
              会员日
              <template v-if="formData.receiveTimeType == 5">
                <a-input
                  type="number"
                  v-model="formData.receiveTimeAmount"
                  :disabled="handle == 'view'"
                  style="width: 100px"
                ></a-input>
                天内可领取
              </template>
            </a-radio>
            <a-radio
              :value="6"
              style="display: block; height: 40px; line-height: 40px"
            >
              指定时间
              <template v-if="formData.receiveTimeType == 6">
                <a-date-picker
                  :disabled-date="disabledDate"
                  :disabled="handle == 'view'"
                  :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
                  v-model="formData.receiveTimeAmount"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 200px"
                />
              </template>
            </a-radio>
          </template>
          <a-radio
            :value="7"
            style="display: block; height: 40px; line-height: 40px"
          >
            指定时间范围
            <template v-if="formData.receiveTimeType == 7">
              <a-date-picker
                :disabled-date="disabledDate"
                :disabled="handle == 'view'"
                :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
                v-model="formData.getStartTime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 200px"
              />
              <span style="padding: 0 10px"> 至 </span>
              <a-date-picker
                :disabled-date="disabledReceiveTimeEndDate"
                :disabled-time="disabledReceiveTimeEndTime"
                :disabled="handle == 'view'"
                :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
                v-model="formData.getEndTime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 200px"
              />
            </template>
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <!-- <a-form-model-item label="领取开始时间" prop="getStartTime">
        <a-date-picker
          :disabled-date="disabledDate"
          :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
          v-model="formData.getStartTime"
          format="YYYY-MM-DD HH:mm:ss"
          style="width:200px"
        />
      </a-form-model-item>

      <a-form-model-item label="领取结束时间" prop="getEndTime">
        <a-date-picker
          :disabled-date="disabledDate"
          :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
          v-model="formData.getEndTime"
          format="YYYY-MM-DD HH:mm:ss"
          style="width:200px"
        />
      </a-form-model-item> -->

      <a-form-model-item prop="">
        <template slot="label">
          <span class="ant-form-item-required">使用时间范围</span>
        </template>
        <a-radio-group
          v-model="formData.useTimeType"
          :disabled="handle == 'view'"
          @change="YXQchange"
        >
          <a-radio
            :value="1"
            style="display: block; height: 40px; line-height: 40px"
          >
            指定时间
            <template v-if="formData.useTimeType == 1">
              <a-date-picker
                :disabled-date="disabledDate"
                :disabled="handle == 'view'"
                :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
                v-model="formData.useStartTime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 200px"
              />
              <span style="padding: 0 10px"> 至 </span>
              <a-date-picker
                :disabled-date="disabledUseTimeTypeEndDate"
                :disabled-time="disabledUseTimeTypeEndTime"
                :disabled="handle == 'view'"
                :show-time="{ defaultValue: Moment('00:00:00', 'HH:mm:ss') }"
                v-model="formData.useEndTime"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 200px"
              />
              内可用
            </template>
          </a-radio>
          <a-radio
            :value="2"
            style="display: block; height: 40px; line-height: 40px"
          >
            领券当日起
            <template v-if="formData.useTimeType == 2">
              <!-- <a-input
                type="number"
                v-model="formData.receiveDaysAble"
                :disabled="handle == 'view'"
                style="width: 100px"
              ></a-input> -->
              <a-input-number
                :min="1"
                :step="1"
                :precision="0"
                v-model="formData.receiveDaysAble"
                :disabled="handle == 'view'"
                style="width: 100px"
              />
              天内有效
            </template>
          </a-radio>
          <a-radio
            v-if="formData.couponType == 3 || formData.couponType == 4"
            :value="3"
            style="display: block; height: 40px; line-height: 40px"
          >
            永久有效
          </a-radio>
        </a-radio-group>
      </a-form-model-item>

      <!--    <a-form-model-item label="使用结束时间" prop="useEndTime">

      </a-form-model-item>-->

      <a-form-model-item :wrapperCol="{ span: 24 }" style="text-align: center">
        <a-button type="primary" v-if="handle != 'view'" @click="handleSubmit"
          >提交</a-button
        >
        <a-button style="margin-left: 8px" @click="backPrePage">返回</a-button>
      </a-form-model-item>
    </a-form-model>
    <MembershipLevelList
      :visible="showMemberLevel"
      :selectedKeys="selectedLevelKeys"
      @cancel="showMemberLevel = false"
      @submit="handleMemberLevelSubmit"
    ></MembershipLevelList>
    <CustomList
      :visible="showCustomList"
      :selectedKeys="customListKeys"
      @cancel="showCustomList = false"
      @submit="handleCustomListSubmit"
    ></CustomList>
    <CommodityList
      :visible="showEnableGoods"
      :selectedKeys="selectedGoodsKeys"
      @cancel="handleCancelGoods"
      @submit="handleGoodsSubmit"
    ></CommodityList>
    <CommodityList
      :visible="showNotEnableGoods"
      :selectedKeys="selectedNotGoodsKeys"
      @cancel="handleCancelGoods"
      @submit="handleNotGoodsSubmit"
    ></CommodityList>
    <CommodityGroupList
      :visible="showEnableGoodsGroup"
      :selectedKeys="selectedGoodsGroupKeys"
      @cancel="handleCancelGoods"
      @submit="handleGoodsGroupSubmit"
    ></CommodityGroupList>
    <CommodityGroupList
      :visible="showNotEnableGoodsGroup"
      :selectedKeys="selectedNotGoodsGroupKeys"
      @cancel="handleCancelGoods"
      @submit="handleNotGoodsGroupSubmit"
    ></CommodityGroupList>
    <DistributionConditions
      :visible="showDistributionConditions"
      :selectedKeys="selectedDistributionConditionsKeys"
      :params="distributionConditionsParams"
      @cancel="showDistributionConditions = false"
      @submit="handleDistributionConditionsSubmit"
    ></DistributionConditions>
    <Preview class="preview" :data="formData"></Preview>
  </a-card>
</template>

<script>
import deepCopy from "@/utils/deepCopy";
import { createOptionsByDict } from "@/utils/dict";
import Moment from "moment";
import MembershipLevelList from "./components/MembershipLevelList";
import CommodityList from "./components/CommodityList";
import CommodityGroupList from "./components/CommodityGroupList";
import DistributionConditions from "./components/DistributionConditions";
import CustomList from "./components/CustomList";
import Preview from "./components/Preview";

export default {
  name: "BaseForm",
  components: {
    MembershipLevelList,
    CommodityList,
    CommodityGroupList,
    DistributionConditions,
    CustomList,
    Preview,
  },
  data() {
    return {
      description:
        "表单页用于向用户收集或验证信息，基础表单常见于数据项较少的表单场景。",
      value: 1,
      couponInfo: {},
      couponList: createOptionsByDict("COUPON_TYPE"), // 优惠券类型
      //发放方式
      distributionMethod: [
        {
          label: "用户领取",
          value: 0,
        },
        {
          label: "系统发放",
          value: 1,
        },
      ],
      useUserList: [
        {
          label: "所有用户均可领取",
          value: 0,
        },
        {
          label: "指定会员等级领取",
          value: 1,
        },
        {
          label: "指定客户可领取",
          value: 2,
        },
      ],
      //使用商品
      useGoodsList: [
        {
          label: "全部商品",
          value: 0,
        },
        {
          label: "指定商品可用",
          value: 2,
        },
        {
          label: "指定商品不可用",
          value: 4,
        },
        {
          label: "指定分类可用",
          value: 1,
        },
        {
          label: "指定分类不可用",
          value: 3,
        },
      ],
      //优惠券获取方式
      acquisitionMethodList: [
        {
          label: "领取",
          value: 0,
        },
        {
          label: "券码兑换",
          value: 1,
        },
      ],
      allowGiftList: [
        {
          label: "允许",
          value: 0,
        },
        {
          label: "不允许",
          value: 1,
        },
      ],
      formData: {
        couponName: "", //优惠券名称
        couponAmount: "", //优惠券金额，单位：元
        couponFullMoneyType: 2,
        couponFullMoney: 0, //使用门槛，订单金额满多少可使用，单位：元
        couponTotal: 0, //优惠券总量，null就是不限量
        couponLimit: "", //限制单人领取的数量
        couponOwnWay: 0, //获取方式，0：领取；1：兑换
        couponType: 0, //优惠券类型，0：满减；1：礼品
        couponIssueType: 0, //优惠券发放方式，0：用户领取；1：新用户注册发放；2、消费满额发放
        useCustomerType: 0, //使用用户类型，0：所有用户均可领取；1：指定会员等级领取；2：指定客户可领取
        couponOwnerLevel: "", //会员等级ids，多个级别逗号分割
        customerIds: "", //客户的ids，多个用逗号分割
        couponUseType: 0, //优惠券使用类型，0：全部；1：指定商品分类；2：指定商品
        enableGoodsGroup: "", //商品分类ids，多个商品分类逗号分割
        enableGoods: "", //	商品ids，多个商品逗号分割
        notEnableGoodsGroup: "", //不可用商品分类ids，多个商品分类逗号分割
        notEnableGoods: "", //不可用商品ids，多个商品逗号分割
        discountRatio: "", //折扣比率，精确到小数点后两位
        mostDiscount: "", //最多优惠，单位：元
        allowGift: 1, //	是否允许转让，默认否，0：允许；1：不允许
        receiveTimeType: 7, // 领取时间范围类型
        receiveTimeAmount: "", // 领取时间天数
        getStartTime: "", //领取开始时间
        getEndTime: "", //领取结束时间
        useTimeType: 1, // 使用时间范围类型 1指定时间范围内 2领券之日起 3永久有效
        useStartTime: "", //使用开始时间
        useEndTime: "", //使用结束时间
        couponDesc: "", //优惠券说明

        couponTotalCustom: 0, //优惠券总量
        couponIssueTypeCustom: 0, //自定义参数   用户领取、系统发放
        mostDiscountCustom: [], //最多优惠

        receiveDaysAble: 0,

        redeemStatus: 0,
        redeemAmount: 0,
      },
      rules: {
        couponType: [{ required: true, message: "请选择优惠券类型" }],
        couponName: [
          { required: true, message: "请输入10个字以内的优惠券名称" },
          { max: 10, message: "优惠券名称10个字以内" },
        ],
        couponAmount: [
          { required: true, message: "请输入优惠券金额" },
          {
            validator: this.validateDiscountNumber,
          },
        ],
        couponFullMoneyType: [{ required: true, message: "请选择使用门槛" }],
        couponTotal: [{ required: true, message: "请输入发放总量" }],
        couponLimit: [{ required: true, message: "请输入限领总量" }],
        couponDesc: [
          { required: true, message: "请输入128个以内的优惠券说明" },
        ],
        // getStartTime:[{ required: true, message: '请选择领取开始时间' }],
        // getEndTime: [{ required: true, message: '请选择下架时间' }],
        useStartTime: [{ required: true, message: "请选择使用开始时间" }],
        useEndTime: [{ required: true, message: "请选择使用结束时间" }],
      },
      //商品及商品分组
      showEnableGoods: false,
      showNotEnableGoods: false,
      showEnableGoodsGroup: false,
      showNotEnableGoodsGroup: false,
      selectedGoodsKeys: [],
      selectedNotGoodsKeys: [],
      selectedGoodsGroupKeys: [],
      selectedNotGoodsGroupKeys: [],
      //会员等级
      showMemberLevel: false,
      selectedLevelKeys: [],
      //发放方式
      showDistributionConditions: false,
      selectedDistributionConditionsKeys: [],
      distributionConditionsParams: {},
      //使用用户 客户可领取
      showCustomList: false,
      customListKeys: [],
    };
  },

  computed: {
    fromType() {
      return this.$route.query.fromType;
    },
    couponId() {
      return this.$route.query.id;
    },
    handle() {
      return this.$route.query.handle;
    },
  },

  created() {
    if (this.fromType == 2 || this.fromType == 3) {
      this.getCouponDetail();
    }
  },
  methods: {
    Moment,
    handleChanage() {
      if (this.formData.couponType == 3 || this.formData.couponType == 4) {
        if (!this.formData.couponIssueTypeCustom) {
          this.formData.couponIssueType = 0;
        } else {
          this.formData.couponIssueType = 4;
        }
      } else {
        this.formData.couponIssueType =
          this.selectedDistributionConditionsKeys.join(",");
      }
    },
    disabledDate(current) {
      //console.log('current',current)
      return current < Moment(Moment().format("YYYY-MM-DD 00:00:00"));
    },
    disabledReceiveTimeEndDate(current) {
      return (
        current &&
        current <
          Moment(
            Moment(this.formData.getStartTime).format("YYYY-MM-DD 00:00:00")
          )
      );
    },
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    },
    disabledReceiveTimeEndTime(current) {
      let hour = Moment(this.formData.getStartTime).format('HH')
      let minute = Moment(this.formData.getStartTime).format('mm')
      let second = Moment(this.formData.getStartTime).format('ss')
      let bD = Number(Moment(this.formData.getStartTime).format('DD'))
      let eD = Number(Moment(current).format('DD'))
      let hA, mA, sA
      if (bD == eD) {
        hA = this.range(0, Number(hour))
        mA = this.range(0, Number(minute))
        sA = this.range(0, Number(second))
      } else {
        hA = this.range(0, 0)
        mA = this.range(0, 0)
        sA = this.range(0, 0)
      }
      return {
        disabledHours: () => hA,
        disabledMinutes: () => mA,
        disabledSeconds: () => sA,
      };
    },
    disabledUseTimeTypeEndDate(current) {
      return (
        current &&
        current <
          Moment(
            Moment(this.formData.useStartTime).format("YYYY-MM-DD 00:00:00")
          )
      );
    },
    range(start, end) {
      const result = [];
      for (let i = start; i < end; i++) {
        result.push(i);
      }
      return result;
    },
    disabledUseTimeTypeEndTime(current) {
      let hour = Moment(this.formData.useStartTime).format('HH')
      let minute = Moment(this.formData.useStartTime).format('mm')
      let second = Moment(this.formData.useStartTime).format('ss')
      let bD = Number(Moment(this.formData.getStartTime).format('DD'))
      let eD = Number(Moment(current).format('DD'))
      let hA, mA, sA
      if (bD == eD) {
        hA = this.range(0, Number(hour))
        mA = this.range(0, Number(minute))
        sA = this.range(0, Number(second))
      } else {
        hA = this.range(0, 0)
        mA = this.range(0, 0)
        sA = this.range(0, 0)
      }
      return {
        disabledHours: () => hA,
        disabledMinutes: () => mA,
        disabledSeconds: () => sA,
      };
    },
    //发放总量切换
    handleCouponTotalChange() {
      if (this.formData.couponTotalCustom == 2) {
        this.formData.couponTotal = 0;
      }
    },
    //使用条件
    handleCouponFullMoneyChange() {
      if (this.formData.couponFullMoneyType == 2) {
        this.formData.couponFullMoney = 0;
      }
    },
    //发放方式
    handleCouponIssueTypeChange() {
      if (this.formData.couponIssueTypeCustom != 1) {
        this.formData.couponIssueType = 0;
      }
    },
    //使用用户
    handleUseCustomerTypeChange() {
      if (this.formData.useCustomerType == 0) {
        this.formData.couponOwnerLevel = "";
        this.formData.customerIds = "";
      } else if (this.formData.useCustomerType == 1) {
        this.formData.customerIds = "";
      } else if (this.formData.useCustomerType == 2) {
        this.formData.couponOwnerLevel = "";
      }
    },
    //使用商品
    handleCouponUseTypeChange() {
      if (this.formData.couponUseType != 1) {
        this.formData.enableGoodsGroup = "";
      } else if (this.formData.couponUseType != 2) {
        this.formData.enableGoods = "";
      }
    },
    // 校验优惠金额不能大于10000
    validateDiscountNumber(rule, value, callback) {
      if (+value > 10000) {
        callback(new Error("请输入小于10000的优惠券金额"));
        return;
      }
      callback();
    },
    // 修改时获取详情
    getCouponDetail() {
      this.$get("/coupon/query", { id: this.couponId }).then((res) => {
        if (res && res.returnCode === 1000) {
          let dataInfo = res.dataInfo || {};
          dataInfo.couponType = dataInfo.couponType.toString();
          //优惠内容
          if (dataInfo.couponType == 2 || dataInfo.couponType == 4) {
            if (parseFloat(dataInfo.mostDiscount) > 0) {
              dataInfo.mostDiscountCustom = [1];
            } else {
              dataInfo.mostDiscountCustom = [];
            }
          }
          //使用门槛
          if (
            parseFloat(dataInfo.couponFullMoney) &&
            parseFloat(dataInfo.couponFullMoney) != -1
          ) {
            dataInfo.couponFullMoneyType = 1;
          } else {
            dataInfo.couponFullMoneyType = 2;
          }

          //发放方式 优惠券发放方式，0：用户领取；1：新用户注册发放；2、消费满额发放
          if (dataInfo.couponType != 3 && dataInfo.couponType != 4) {
            if (parseFloat(dataInfo.couponIssueType) > 0) {
              dataInfo.couponIssueTypeCustom = 1;
              this.selectedDistributionConditionsKeys = dataInfo.couponIssueType
                .split(",")
                .map((item) => parseFloat(item));
              this.distributionConditionsParams = {
                price: dataInfo.orderAmountIssue,
              };
            } else {
              dataInfo.couponIssueTypeCustom = 0;
            }
          } else {
            dataInfo.couponIssueType = Number(dataInfo.couponIssueType);
          }

          if (dataInfo.useCustomerType == 1) {
            //会员等级
            this.selectedLevelKeys = dataInfo.couponOwnerLevel.split(",");
          } else if (dataInfo.useCustomerType == 2) {
            //指定客户领取
            this.customListKeys = dataInfo.customerIds.split(",");
          }
          //商品、商品分组
          if (dataInfo.couponUseType == 1) {
            //指定商品分类
            this.selectedGoodsGroupKeys = dataInfo.enableGoodsGroup.split(",");
          } else if (dataInfo.couponUseType == 2) {
            //指定商品
            this.selectedGoodsKeys = dataInfo.enableGoods.split(",");
          } else if (dataInfo.couponUseType == 3) {
            //不可用商品分类
            this.selectedNotGoodsGroupKeys =
              dataInfo.notEnableGoodsGroup.split(",");
          } else if (dataInfo.couponUseType == 4) {
            //不可用商品
            this.selectedNotGoodsKeys = dataInfo.notEnableGoods.split(",");
          }

          if (dataInfo.couponTotal > 0) {
            dataInfo.couponTotalCustom = 1;
          } else {
            dataInfo.couponTotalCustom = 2;
          }
          if (!dataInfo.receiveTimeType || dataInfo.receiveTimeType == 7) {
            dataInfo.receiveTimeType = 7;
            dataInfo.receiveTimeAmount = "";
          }
          /*=========*/
          if (!dataInfo.useTimeType) {
            if (!!dataInfo.receiveDaysAble) {
              dataInfo.useTimeType = 2;
              dataInfo.useStartTime = "";
              dataInfo.useEndTime = "";
            } else {
              dataInfo.useTimeType = 1;
            }
          }

          this.formData = dataInfo;
        }
      });
    },
    number2Price(value, multiple = 100) {
      value = +value || 0;
      if (!value) return 0;
      return +(value / multiple).toFixed(2);
    },
    formDate(datetime) {
      let date = new Date(datetime);
      //console.log(date);
      let y = date.getFullYear();
      let m = date.getMonth() + 1;
      m = m >= 10 ? m : "0" + m;
      let d = date.getDate();
      d = d >= 10 ? d : "0" + d;
      let hour = date.getHours();
      hour = hour >= 10 ? hour : "0" + hour;
      let min = date.getMinutes();
      min = min >= 10 ? min : "0" + min;
      let sec = date.getSeconds();
      sec = sec >= 10 ? sec : "0" + sec;
      return `${y}-${m}-${d} ${hour}:${min}:${sec}`;
    },
    // handler
    handleSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        console.log("this.formData", this.formData);
        if (valid) {
          // this.formData.getStartTime = this.formDate(this.formData.getStartTime);
          // this.formData.getEndTime = this.formDate(this.formData.getEndTime);
          // if (this.formData.useStartTime!=''){
          //   this.formData.useStartTime = this.formDate(this.formData.useStartTime);
          // }
          // if (this.formData.useEndTime!=''){
          //   this.formData.useEndTime = this.formDate(this.formData.useEndTime);
          // }

          //优惠内容
          if (this.formData.couponType == 2 || this.formData.couponType == 4) {
            //this.formData.couponAmount=null;
            if (
              !this.formData.discountRatio ||
              this.formData.discountRatio == -1
            ) {
              this.$message.error("请输入折扣比率");
              return;
            }
            if (
              this.formData.mostDiscountCustom &&
              this.formData.mostDiscountCustom.length > 0 &&
              this.formData.mostDiscountCustom[0] == 1
            ) {
              if (parseFloat(this.formData.mostDiscount) == 0) {
                this.$message.error("请输入最多优惠元");
                return;
              }
            } else {
              this.formData.mostDiscount = 0;
            }
          } else {
            this.formData.mostDiscount = "";
          }

          //使用门槛
          if (this.formData.couponFullMoneyType == 1) {
            //let isZero=(this.formData.couponFullMoney!==0 && this.formData.couponFullMoney!=='0' && this.formData.couponFullMoney!=='0.00');
            if (
              !parseFloat(this.formData.couponFullMoney) ||
              parseFloat(this.formData.couponFullMoney) == -1
            ) {
              this.$message.error("请输入订单金额满多少可以使用");
              return;
            }
            if (
              this.formData.couponType != 2 &&
              this.formData.couponType != 4
            ) {
              if (
                parseFloat(this.formData.couponAmount) >
                parseFloat(this.formData.couponFullMoney)
              ) {
                this.$message.error("订单满多少可用不能小于金额");
                return;
              }
            }
          } else {
            this.formData.couponFullMoney = 0;
          }

          //发放方式   	优惠券发放方式，0：用户领取；1：新用户注册发放；2、消费满额发放
          if (this.formData.couponIssueTypeCustom == 1) {
            if (
              !this.formData.couponIssueType ||
              this.formData.couponFullMoney == -1
            ) {
              this.$message.error("请选择发放条件");
              return;
            }
          }

          //使用用户
          if (this.formData.useCustomerType == 1) {
            if (!this.formData.couponOwnerLevel) {
              this.$message.error("请选择会员等级领取");
              return;
            }
          } else if (this.formData.useCustomerType == 2) {
            if (!this.formData.customerIds) {
              this.$message.error("请选择客户领取");
              return;
            }
          }

          //使用商品 优惠券使用类型，0：全部；1：指定商品分类；2：指定商品；3：不可用商品分类；4：不可用商品
          if (this.formData.couponUseType == 1) {
            //指定商品分类
            if (!this.formData.enableGoodsGroup) {
              this.$message.error("请选择指定商品分类");
              return;
            }
          } else if (this.formData.couponUseType == 2) {
            //指定商品
            if (!this.formData.enableGoods) {
              this.$message.error("请选择指定商品");
              return;
            }
          } else if (this.formData.couponUseType == 3) {
            //不可用商品分类
            if (!this.formData.notEnableGoodsGroup) {
              this.$message.error("请选择不可用商品分类");
              return;
            }
          } else if (this.formData.couponUseType == 4) {
            //不可用商品
            if (!this.formData.notEnableGoods) {
              this.$message.error("请选择不可用商品");
              return;
            }
          }

          if (
            this.formData.couponTotalCustom == 1 &&
            this.formData.couponLimit > this.formData.couponTotal
          ) {
            this.$message.error("限领总量不能大于发放总量");
            return;
          }
          if (this.formData.receiveTimeType == 7) {
            if (!this.formData.getStartTime) {
              this.$message.error("请选择领取开始时间");
              return;
            }
            if (!this.formData.getEndTime) {
              this.$message.error("请选择领取结束时间");
              return;
            }
            if (
              new Date(this.formData.getStartTime).getTime() >
              new Date(this.formData.getEndTime)
            ) {
              this.$message.error("领取开始时间不能大于结束时间");
              return;
            }
            if (this.formData.useTimeType == 1) {
              if (
                new Date(this.formData.useStartTime).getTime() >
                new Date(this.formData.useEndTime)
              ) {
                this.$message.error("使用开始时间不能大于结束时间");
                return;
              }
              if (
                new Date(this.formData.useStartTime).getTime() <
                new Date(this.formData.getStartTime)
              ) {
                this.$message.error("使用开始时间不能小于领取开始时间");
                return;
              }
            }
          } else if (this.formData.receiveTimeType == 6) {
            if (!this.formData.receiveTimeAmount) {
              this.$message.error("请选择指定日期");
              return;
            }
          } else if (this.formData.receiveTimeType != 1) {
            if (!this.formData.receiveTimeAmount) {
              this.$message.error("请输入天数");
              return;
            }
          }

          let params = deepCopy(this.formData);
          params.couponAmount = parseFloat(params.couponAmount);
          params.couponFullMoney = parseFloat(params.couponFullMoney);
          params.orderAmountIssue = parseFloat(params.orderAmountIssue) || "";
          if (params.couponType != 3 && params.couponType != 4) {
            if (!params.couponIssueTypeCustom) {
              params.couponIssueType = 0;
            }
          }

          if (!params.orderAmountIssue) {
            params.orderAmountIssue = -1;
          }
          if (!params.couponFullMoney) {
            params.couponFullMoney = -1;
          }
          if (params.couponTotalCustom != 1) {
            params.couponTotal = -1;
            params.couponStocks = -1;
          } else {
            params.couponStocks = params.couponTotal;
          }
          if (params.couponType == 2 || params.couponType == 4) {
            params.couponAmount = -1;
            if (!params.mostDiscount) {
              params.mostDiscount = -1;
            }
          } else {
            params.discountRatio = -1; //打折
            params.mostDiscount = -1; //最多优惠
          }

          // return
          if (this.formData.couponType == 3) {
            this.$confirm({
              title: "提示",
              content: "优惠券创建后将不可以修改且立即生效。请确认是否提交？",
              okText: "确认",
              cancelText: "取消",
              onOk: () => {
                //this.$router.go(-1);
                this.updateCouponData(params);
              },
            });
          } else {
            this.updateCouponData(params);
          }
        } else {
          return false;
        }
      });
    },
    backPrePage(e, record) {
      e.stopPropagation();
      // this.$confirm({
      //   title: "提示",
      //   content: "确定要返回上一页？",
      //   okText: "确认返回",
      //   cancelText: "取消",
      //   onOk: () => {
      //     //this.$router.go(-1);
      //     this.$router.push({
      //       name:'MarketingCoupon',
      //       query: {
      //         current:this.$route.query.current||1
      //       }
      //     })
      //   },
      // });
      this.$router.push({
        name: "MarketingCoupon",
        query: {
          current: this.$route.query.current || 1,
        },
      });
    },
    updateCouponData(value) {
      value.couponType = Number(value.couponType);
      let url = "/coupon/add";
      if (this.fromType == 2) {
        url = "/coupon/update";
        value.id = this.couponId;
      } else if (this.fromType == 1) {
        value.couponStatus = 0;
      } else {
        value.id = "";
        value.couponStatus = 0;
      }
      this.$post(url, { ...value }).then((res) => {
        if (res && res.returnCode === 1000) {
          this.$message.success("保存成功！");
          this.$router.push({
            name: "MarketingCoupon",
            query: {
              current: this.$route.query.current || 1,
              submit: true,
            },
          });
        }
      });
    },
    handleMemberLevelSubmit(selectedKeys) {
      this.formData.couponOwnerLevel = selectedKeys.join(",");
      this.selectedLevelKeys = selectedKeys;
      this.showMemberLevel = false;
    },
    //选择发放条件
    handleDistributionConditionsSubmit(selectedKeys, data) {
      this.formData.couponIssueType = selectedKeys.join(",");
      this.selectedDistributionConditionsKeys = selectedKeys;
      this.distributionConditionsParams = {
        price: data.price,
      };
      this.formData.orderAmountIssue = parseFloat(data.price) || "";
      this.showDistributionConditions = false;
    },
    handleCouponIssueTypeCustomChange() {
      if (this.formData.couponIssueTypeCustom == 0) {
        this.formData.couponIssueType = "";
        this.formData.orderAmountIssue = "";
      }
    },
    //客户
    handleCustomListSubmit(selectedKeys) {
      this.formData.customerIds = selectedKeys.join(",");
      this.customListKeys = selectedKeys;
      this.showCustomList = false;
    },
    //取消选择商品及分类
    handleCancelGoods() {
      this.showEnableGoods = false;
      this.showNotEnableGoods = false;
      this.showEnableGoodsGroup = false;
      this.showNotEnableGoodsGroup = false;
    },
    handleClearGoods() {
      this.formData.enableGoods = "";
      this.formData.notEnableGoods = "";
      this.formData.enableGoodsGroup = "";
      this.formData.notEnableGoodsGroup = "";
      this.selectedGoodsKeys = [];
      this.selectedNotGoodsKeys = [];
      this.selectedGoodsGroupKeys = [];
      this.selectedNotGoodsGroupKeys = [];
    },
    //商品显示
    handleShowEnableGoodsChange() {
      this.showEnableGoods = true;
    },
    handleShowNotEnableGoodsChange() {
      this.showNotEnableGoods = true;
    },
    handleShowEnableGoodsGroupChange() {
      this.showEnableGoodsGroup = true;
    },
    handleShowNotEnableGoodsGroupChange() {
      this.showNotEnableGoodsGroup = true;
    },
    //商品提交
    handleGoodsSubmit(selectedKeys) {
      this.handleClearGoods();
      this.formData.enableGoods = selectedKeys.join(",");
      this.selectedGoodsKeys = selectedKeys;
      this.showEnableGoods = false;
    },
    handleNotGoodsSubmit(selectedKeys) {
      this.handleClearGoods();
      this.formData.notEnableGoods = selectedKeys.join(",");
      this.selectedNotGoodsKeys = selectedKeys;
      this.showNotEnableGoods = false;
    },
    handleGoodsGroupSubmit(selectedKeys) {
      this.handleClearGoods();
      this.formData.enableGoodsGroup = selectedKeys.join(",");
      this.selectedGoodsGroupKeys = selectedKeys;
      this.showEnableGoodsGroup = false;
    },
    handleNotGoodsGroupSubmit(selectedKeys) {
      this.handleClearGoods();
      this.formData.notEnableGoodsGroup = selectedKeys.join(",");
      this.selectedNotGoodsGroupKeys = selectedKeys;
      this.showNotEnableGoodsGroup = false;
    },
    receiveTimeTypeChange(e) {
      if (e.target.value != 7) {
        if (e.target.value == 6) {
          this.formData.receiveTimeAmount = "";
        } else {
          this.formData.receiveTimeAmount = 0;
        }
      }
    },
    YXQchange(e) {
      if (e.target.value == 1) {
        // this. formData.receiveDaysAble =null
        this.formData.receiveDaysAble = 0;
      }
      if (e.target.value == 2) {
        this.formData.useStartTime = "";
        this.formData.useEndTime = "";
      }
    },
    redeemExChange(e) {
      if (this.formData.redeemStatus == 0) {
        this.formData.redeemAmount = null;
      }
      /*console.log(e.target.value)
      console.log(this.formData.redeemStatus)*/
    },
  },
};
</script>

<style lang="less" scoped>
.preview {
  position: absolute;
  left: 70%;
  top: 400px;
  width: 360px;
}
</style>
